package com.zz.yt.lib.login.delegate.login.base;

import android.annotation.TargetApi;
import android.content.Context;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;

import androidx.annotation.NonNull;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.zz.yt.lib.login.checker.FingerManager;
import com.zz.yt.lib.login.constant.ILoginListener;

import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;

import javax.crypto.KeyGenerator;

/**
 * 指纹认证（获取存储的账号，刷新token）
 *
 * @author qf
 * @version 1.0.9
 **/
public abstract class BaseFingerDelegate extends BaseSigInDelegate {

    private ILoginListener mLoginListener = null;
    private BiometricPrompt mBiometricPrompt;
    private BiometricPrompt.PromptInfo promptInfo;


    @Override
    public void onAttach(@NonNull Context activity) {
        super.onAttach(activity);
        //这里是类型转换，而不是判断
        if (activity instanceof ILoginListener) {
            mLoginListener = (ILoginListener) activity;
        }
    }

    @Override
    protected void inGradePermission() {
        super.inGradePermission();
        promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle("指纹验证")
                .setSubtitle("请触摸指纹传感器")
                .setNegativeButtonText("取消")
                .build();
        if (getActivity() != null) {
            mBiometricPrompt = new BiometricPrompt(getActivity(), ContextCompat.getMainExecutor(context),
                    new BiometricPrompt.AuthenticationCallback() {
                        @Override
                        public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                            super.onAuthenticationError(errorCode, errString);
                            LogUtils.d("onAuthenticationError 认证错误： " + errString);
                        }

                        @Override
                        public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
                            super.onAuthenticationSucceeded(result);
                            LogUtils.d("onAuthenticationSucceeded 认证成功： " + result);
                            onAuthenticationGood();
                        }

                        @Override
                        public void onAuthenticationFailed() {
                            super.onAuthenticationFailed();
                            LogUtils.d("onAuthenticationFailed 认证失败");
                        }
                    });
            initFinger();
        }
    }

    /**
     * 指纹认证成功调用。
     */
    protected void onAuthenticationGood() {
        if (mLoginListener != null) {
            mLoginListener.onSignIn(getAccount(), getPassword());
        }
    }

    /**
     * 弹框提示指纹登录。
     */
    protected void initFinger() {
        if (supportFingerprint()) {
            initKey();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //仿网络请求
        Latte.getHandler().postDelayed(this::initFinger, 200);
    }

    @TargetApi(23)
    private void initKey() {
        try {
            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(FingerManager.DEFAULT_KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
            keyGenerator.init(builder.build());
            keyGenerator.generateKey();
            if (mBiometricPrompt != null && ObjectUtils.isNotEmpty(getAccount())
                    && ObjectUtils.isNotEmpty(getPassword())) {
                mBiometricPrompt.authenticate(promptInfo);
            }
        } catch (InvalidAlgorithmParameterException e) {
            ToastUtils.showShort("您至少需要在本机系统设置中添加一个指纹");
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }

}
